<template>
  <div class="pub">
    <div class="pub-box">
      <a-steps :current="current" size="small">
        <a-step v-for="item in steps" :key="item.title" :title="item.title" />
      </a-steps>
      <div class="steps-content">
        <div v-if="steps[current].id === 1">
          <a-form
            :model="formState"
            ref="formRef"
            name="basic"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
            @finish="onFinish"
            @finishFailed="onFinishFailed"
          >
            <a-form-item
              label="名称"
              name="releaseName"
              :rules="[{ required: true, message: '请输入名称' }]"
            >
              <a-input
                placeholder="请输入内容"
                v-model:value="formState.releaseName"
              />
            </a-form-item>

            <a-form-item
              label="年月"
              name="wageDate"
              :rules="[{ required: true, message: '请选择月份' }]"
            >
              <a-date-picker
                v-model:value="formState.wageDate"
                picker="month"
                placeholder="请选择月份"
              />
            </a-form-item>
            <a-form-item
              label="工资模板"
              name="templateId"
              :rules="[{ required: true, message: '请选择' }]"
            >
              <a-select
                v-model:value="formState.templateId"
                :options="modelList"
                placeholder="请选择"
                @change="changeTem"
                :fieldNames="{ label: 'templateName', value: 'id' }"
              />
              <span
                class="downModel"
                v-if="formState.templateId"
                @click="downLoadModelFn(formState.templateId)"
                >下载该模板</span
              >
            </a-form-item>
          </a-form>
        </div>
        <div v-if="steps[current].id === 2" class="upload-box">
          <a-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :multiple="false"
            :action="action"
            :headers="{ Authorization: token }"
            @change="uploadFile"
            :before-upload="beforeUpload"
          >
            <svg-icon icon-class="upload" class="ant-upload-icon"></svg-icon>
            <p class="ant-upload-text">
              将选定文件拖拽至框内或<span class="ant-upload-text_btn"
                >点击上传</span
              >
            </p>
            <p class="ant-upload-hint">
              支持.xls、.xlsx、.xlsm格式的文件，文件大小不能超过2M
            </p>
            <template #itemRender="{ file }">
              <div style="margintop: 28px; display: flex; alignitems: center">
                <img
                  src="@/assets/img/uploadFile.png"
                  alt=""
                  class="upload-fileImg"
                />
                <div style="width: 100%">
                  <span class="fileName">{{ file.name }}</span>
                  <a-progress
                    strokeWidth="2"
                    :percent="file.percent"
                    size="small"
                    :showInfo="false"
                    strokeColor="#3E77FA"
                  />
                </div>
              </div>
            </template>
          </a-upload-dragger>
          <div class="errorMsg">{{ errorMsg }}</div>
        </div>
        <div
          v-if="steps[current].id === 3"
          style="width: 100%; padding: 0 24px"
        >
          <a-table
            :dataSource="dataSource"
            :columns="columns"
            :pagination="false"
            bordered
            :scroll="{
              x: '-webkit-max-content' || '-moz-max-content' || 'intrinsic',
            }"
          />
        </div>
      </div>
      <div class="steps-action">
        <a-button v-if="current > 0" @click="prev" class="lastBtn"
          >上一步</a-button
        >
        <a-button
          v-if="current < steps.length - 1"
          type="primary"
          @click="next"
          class="nextBtn"
          >下一步</a-button
        >
        <a-button
          v-if="current == steps.length - 1"
          type="primary"
          @click="publish"
        >
          发布
        </a-button>
      </div>
      <a-modal
        :visible="visible"
        title="姓名重复"
        :width="962"
        style="top: 50px"
        class="modal-box"
        @cancel="visible = false"
      >
        <div
          class="box-item"
          v-for="(item, index) in repeatPersonList"
          :key="index"
        >
          <p class="name">
            重复姓名{{ index + 1 }}：{{ item.teachers[0].name }}
          </p>
          <div class="item-info">
            <p v-for="i in item.datas" :key="i.itemValue">
              <span>{{ i.itemName }}</span>
              <span>{{ i.itemValue }}</span>
            </p>
          </div>
          <p>请仔细核对以上工资条对应的人员信息</p>
          <div class="person-info">
            <a-radio-group v-model:value="item.userId">
              <a-radio
                :value="`${k.personId}`"
                class="person-item"
                v-for="k in item.teachers"
                :key="k.personId"
              >
                <div>{{ k.name }} {{ k.sex === "XB_1" ? "男" : "女" }}</div>
                <div class="person-item-grey">身份证：{{ k.idcardNo }}</div>
                <div class="person-item-grey">电话：{{ k.phone }}</div>
              </a-radio>
            </a-radio-group>
          </div>
        </div>
        <template #footer>
          <div class="btn-group">
            <a-button class="modal-btnOff" @click="visible = false"
              >取消</a-button
            >
            <a-button class="modal-btnSure" @click="handleRepeatFn"
              >确认</a-button
            >
          </div>
        </template>
      </a-modal>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { saveAs } from "file-saver";
import {
  getSalaryModelList,
  addFirstStep,
  downLoadModel,
  UpdateFirstStep,
  uploadModelNext,
  getSalaryData,
  publishSalary,
  handleRepeat,
} from "@/service/modules/salary/pub";
import dayjs from "dayjs";
import localCache from "@/utils/cache";
import { BASE_URL } from "@/service/request/config";
import { SYS_TOKEN } from "@/utils/global-constant";
import { message, Modal } from "ant-design-vue";
import router from "@/router";

getSalaryModel();
interface FormState {
  releaseName: string;
  wageDate: string;
  templateId: boolean;
}

const dataSource = ref([]);
const columns = ref([]);
const modelList = ref([]);
const fileList = ref([]);
const formRef = ref(null);
const current = ref<Number>(0);
const baseInfoId = ref<Number>(0);
const secendFlag = ref(false);
const hasRepeat = ref(false);
const repeatPersonList = ref([]);
const visible = ref(false);
const action = ref();
const errorMsg = ref("");
const year = new Date().getFullYear();
const month =
  new Date().getMonth() < 10
    ? "0" + new Date().getMonth()
    : new Date().getMonth();
const token = localCache.getCache(SYS_TOKEN);
const steps = reactive([
  {
    id: 1,
    title: "填写基本信息",
  },
  {
    id: 2,
    title: "上传工资明细表",
  },
  {
    id: 3,
    title: "确认上传信息",
  },
]);

const formState = ref<FormState>({
  releaseName: "",
  wageDate: dayjs(year + "-" + month, "YYYY-MM"),
  templateId: "",
});

// 下一步
const next = async () => {
  console.log(typeof current.value);
  switch (current.value) {
    case 0:
      formRef.value.validateFields().then(async (v) => {
        if (!baseInfoId.value) {
          const { code, data } = await addFirstStep({
            ...formState.value,
            wageDate: dayjs(formState.value.wageDate).format("YYYY-MM"),
          });
          if (code === 0) {
            baseInfoId.value = data.id;
            action.value =
              BASE_URL + "/api/v1/web/wage/release/import/" + baseInfoId.value;
          }
        } else {
          await UpdateFirstStep({
            ...formState.value,
            id: baseInfoId.value,
            wageDate: dayjs(formState.value.wageDate).format("YYYY-MM"),
          });
        }
        current.value++;
      });
      break;
    case 1:
      // errorMsg.value = "请上传文件";
      if (secendFlag.value) {
        modelSuccessFn();
      } else {
        if (!hasRepeat.value) {
          message.info("请上传对应模板文件");
        }
      }
      if (hasRepeat.value) {
        // 弹出人员重复 选择框
        visible.value = true;
      }
      break;
    default:
      break;
  }
  // current.value++;
};
// 上一步
const prev = () => {
  if (current.value === 2) {
    if (hasRepeat.value) {
      secendFlag.value = false;
    }
  }
  // if (current.value === 1) {
  //   // 回到第一步 重新上传文件模板
  //   secendFlag.value = false;
  // }
  current.value--;
};
// 发布工资
const publish = () => {
  Modal.confirm({
    title: "是否确认发布此工资信息",
    icon: createVNode(ExclamationCircleOutlined),
    async onOk() {
      const { code } = await publishSalary(baseInfoId.value);
      if (code === 0) {
        router.push("/salary/pubSuccess");
      }
    },
    onCancel() {
      console.log("Cancel");
    },
    class: "test",
  });
};
// 更改选择下拉模板
const changeTem = () => {
  secendFlag.value = false;
};
// 下载模板
const downLoadModelFn = async (id: string) => {
  const { code, data } = await downLoadModel(id);
  if (code === 0) {
    let templateName = modelList.value.find(
      (item) => item.id === formState.value.templateId
    )?.templateName;
    saveAs(data.url, templateName);
  }
};
// 文件上传前
const beforeUpload = (f) => {
  const { name, size } = f;
  const MaxSize = 2 * 1024 * 1024;
  const type = name.replace(/.+\./, "");
  if (type !== "xls" && type !== "xlsx" && type !== "xlsm") {
    message.error("文件格式只支持xls、xlsx、xlsm");
    return false;
  }
  if (size > MaxSize) {
    message.error("文件大小不超过2M");
    return false;
  }
};
// 上传文件
const uploadFile = async (v) => {
  const {
    file: { response },
  } = v;
  if (response.code === 0) {
    fileList.value = [];
    fileList.value[0] = v.file;
    errorMsg.value = "";
    secendFlag.value = true;
    hasRepeat.value = false;
    message.success("上传成功");
  } else {
    fileList.value = [];
    errorMsg.value = response.msg;
    secendFlag.value = false;
    if (response.code === -2 && response.msg === "有重名人员需要处理") {
      repeatPersonList.value = response.data;
      hasRepeat.value = true;
    }
  }
};
// 提交重复数据
const handleRepeatFn = async () => {
  const _arry = repeatPersonList.value.map((i) => {
    return {
      userId: i.userId,
      rowNum: i.rowNum,
    };
  });
  const res = _arry.some((i) => i.userId);
  const arry = _arry.filter((i) => i.userId !== undefined);
  if (!res) {
    message.warning("请选择人员");
    return false;
  }
  if (arry.length !== repeatPersonList.value.length) {
    message.warning("请确认重复人员");
    return false;
  }
  const params = {
    releaseId: baseInfoId.value,
    repeatRets: arry,
  };
  const { code } = await handleRepeat(params);
  if (code === 0) {
    secendFlag.value = true;
    visible.value = false;
    modelSuccessFn();
  }
};
// 模板上传成功后的操作
const modelSuccessFn = async () => {
  const res = await uploadModelNext(baseInfoId.value);
  if (res.code === 0) {
    current.value++;
    const { code, data } = await getSalaryData(baseInfoId.value);
    if (code === 0) {
      columns.value = data.columns;
      dataSource.value = data.dataSource;
    }
  } else {
    message.error("文件上传不成功");
  }
};
// 获取工资发布模板列表
async function getSalaryModel() {
  const { code, rows } = await getSalaryModelList({
    pageNum: 1,
    pageSize: 999,
  });
  if (code === 0) {
    modelList.value = rows;
    rows.map((i) => {
      if (i.isDefault) {
        formState.value.templateId = i.id;
      }
    });
  }
}
</script>
<style lang="less" scoped>
.pub {
  background: #fff;
  padding: 30px 0;
  height: calc(100vh - 112px);
}
.pub-box {
  // width: 851px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}
.steps-content {
  display: flex;
  flex: 2;
  justify-content: center;
  margin-top: 62px;
}
.steps-action {
  text-align: center;
}
:deep(.ant-form-item-control) {
  width: 400px;
}
:deep(.ant-picker) {
  width: 100%;
}
.downModel {
  position: absolute;
  right: -74px;
  top: 5px;
  cursor: pointer;
  color: #3e77fa;
}
.errorMsg {
  color: red;
  margin-top: 28px;
}
.modal-box {
  padding: 32px;
  .btn-group {
    height: 80px;
  }
  .modal-btnOff,
  .modal-btnSure {
    width: 89px;
    height: 32px;
    line-height: 32px;
    border: 1px solid #3e77fa;
    border-radius: 6px;
    padding: 0;
  }
  .modal-btnOff {
    color: #3e77fa;
  }
  .modal-btnSure {
    color: #ffffff;
    background: #3e77fa;
  }
}
.box-item {
  border: 1px solid #e7e9eb;
  padding: 16px;
  width: 430px;
  display: inline-block;
  .name {
    font-size: 14px;
    color: #303233;
    line-height: 24px;
    font-weight: 500;
  }
}
.item-info {
  background: #f2f4f7;
  width: 100%;
  padding: 16px;
  margin-bottom: 16px;
}
.item-info > p {
  display: flex;
  justify-content: space-between;
  color: #616466;
  font-size: 14px;
  max-height: 207px;
  overflow-y: scroll;
}
.person-item {
  border: 1px solid #e7e9eb;
  width: 197px;
}
.person-item-grey {
  font-size: 12px;
  line-height: 20px;
  color: #aaaeb2;
  position: relative;
  left: -23px;
}
:deep(.ant-radio-wrapper) {
  margin-right: 0;
  padding: 8px 16px;
}
:deep(.ant-radio-group) {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.nextBtn {
  border-radius: 6px;
  background: #3e77fa;
  border: 1px solid #3e77fa;
}
.lastBtn {
  border-radius: 6px;
  background: #f3f6fd;
  border: 1px solid #3e77fa;
  color: #3e77fa;
}
</style>
<style lang="less" scoped>
.campus-salary-web {
  cursor: pointer;
}
:deep(.ant-steps) {
  .ant-steps-item {
    .ant-steps-item-title {
      color: #000000;
    }
  }
  .ant-steps-item-active {
    .ant-steps-item-icon {
      background: #3e77fa;
    }
    .ant-steps-item-title {
      color: #3e77fa;
    }
  }
  .ant-steps-item-finish {
    .ant-steps-item-icon {
      border-color: #23bf71;
      .ant-steps-icon {
        color: #23bf71;
      }
    }
    .ant-steps-item-title {
      color: #23bf71;
    }
  }
}

.upload-box {
  width: 800px;
  height: 240px;
  background: #ffffff;
  :deep(.ant-upload) {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: #ffffff;
    &-icon {
      font-size: 33px;
    }
    &-text {
      margin: 16px 0 !important;
      font-size: 14px !important;
      color: #616366 !important;
      &_btn {
        color: #3e77fa;
      }
    }
    &-hint {
      color: #aaaeb2 !important;
    }
  }
  .upload-fileImg {
    width: 24px;
    height: 24px;
    margin-right: 10px;
    margin-top: 13px;
  }
  .fileName {
    position: relative;
    top: 10px;
  }
}
/deep/ .ant-steps {
  margin: auto;
  width: 60%;
}
</style>
